import os
import re
import pdfplumber

def extract_invoice_info(pdf_path):
    """
    从PDF中提取发票信息
    """
    text_all = ""
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            page_text = page.extract_text()
            if page_text:
                text_all += page_text + "\n"

    # 统一空白字符，便于正则匹配
    normalized_text = re.sub(r"\s+", " ", text_all)

    # 判断是否为滴滴出行行程单
    is_didi_trip = "滴滴出行-行程单" in normalized_text

    # 提取金额（针对滴滴出行行程单）
    didi_amount_match = re.search(r"合计(\d+\.\d+)元", normalized_text)
    didi_amount = didi_amount_match.group(1) if didi_amount_match else ""

    # 判断是否为高德地图打车行程单
    is_amap_trip = "高德地图—打车——行程单" in normalized_text

    # 提取金额（针对高德地图打车行程单）
    amap_amount_match = re.search(r"合计(\d+\.\d+)元", normalized_text)
    amap_amount = amap_amount_match.group(1) if amap_amount_match else ""

    # 1. 提取名称（第二个名称字段作为开具方）
    name_pattern = re.compile(r"名称[:：]\s*(.*?)\s")
    name_matches = name_pattern.findall(normalized_text)
    issuer = name_matches[1].strip() if len(name_matches) >= 2 else ""

    # 2. 提取发票号码
    invoice_number_match = re.search(r"发票号码[:：]\s*([A-Za-z0-9\-]+)", normalized_text)
    invoice_number = invoice_number_match.group(1).strip() if invoice_number_match else ""

    # 3. 提取含税金额（小写）
    amount_match = re.search(r"（小写）\s*¥?\s*([\d.,]+)", normalized_text)
    if amount_match:
        amount_small = f"{amount_match.group(1).strip()}元"
    else:
        # 尝试更简单的匹配方式
        amount_match = re.search(r"（小写）\s*([\d.,]+)", normalized_text)
        if amount_match:
            amount_small = f"{amount_match.group(1).strip()}元"
        else:
            amount_small = ""

    # 4. 判断是否是铁路电子发票
    is_railway_invoice = bool(re.search(r"电子发票.*铁路|铁.*电子客票|铁路电子客票", normalized_text, re.IGNORECASE))

    # 5. 如果是铁路电子发票，额外提取发票号码和票价
    railway_invoice_number = ""
    railway_amount = ""

    if is_railway_invoice:
        # 提取发票号码（支持中英文冒号）
        railway_invoice_number_match = re.search(r"发票号码[:：]\s*([A-Za-z0-9\-]+)", normalized_text)
        railway_invoice_number = railway_invoice_number_match.group(1).strip() if railway_invoice_number_match else ""

        # 提取票价（支持前缀 ¥ 和空格）
        railway_amount_match = re.search(r"￥\s*([\d\.,]+)", normalized_text)
        if railway_amount_match:
            railway_amount = f"{railway_amount_match.group(1).replace(',', '').strip()}元"

    return (
        issuer,
        invoice_number,
        amount_small,
        is_railway_invoice,
        railway_invoice_number,
        railway_amount,
        is_didi_trip,
        didi_amount,
        is_amap_trip,
        amap_amount
    )

def batch_rename_invoices(folder_path):
    """
    批量处理PDF文件并重命名
    """
    all_files = [f for f in os.listdir(folder_path) if f.lower().endswith(".pdf")]
    all_files.sort()

    total = len(all_files)
    if total == 0:
        print("指定文件夹中没有找到任何 PDF 文件。")
        return

    print(f"开始处理 {total} 个 PDF 文件...")

    for idx, filename in enumerate(all_files, start=1):
        old_path = os.path.join(folder_path, filename)

        try:
            info = extract_invoice_info(old_path)
            issuer, invoice_number, amount_small, is_railway_invoice, railway_invoice_number, railway_amount, is_didi_trip, didi_amount, is_amap_trip, amap_amount = info

            seq = str(idx).zfill(2)  # 序号补零

            if is_amap_trip and amap_amount:
                new_name = f"{seq}-高德地图打车行程单-{amap_amount}元.pdf"
            elif is_didi_trip and didi_amount:
                new_name = f"{seq}-滴滴出行行程单-{didi_amount}元.pdf"
            elif is_railway_invoice:
                new_name = f"{seq}-铁路电子客票-{railway_invoice_number}-{railway_amount}.pdf"
            else:
                # 添加判断，如果提取到金额，则包含在文件名中
                if amount_small:
                    new_name = f"{seq}-{issuer}-{invoice_number}-{amount_small}.pdf"
                else:
                    new_name = f"{seq}-{issuer}-{invoice_number}.pdf"

            # 清理非法字符
            new_name = new_name.replace(" ", "").replace("/", "-").replace("\\", "-")

            new_path = os.path.join(folder_path, new_name)
            os.rename(old_path, new_path)

            print(f"[成功] {filename} -> {new_name}")
        except Exception as e:
            print(f"[失败] 重命名失败: {filename}，错误：{e}")
if __name__ == "__main__":
    # 替换为你本地的目标文件夹路径
    folder_path = r"C:\Users\guoya\Desktop\沪昆高速公路昌傅至金鱼石段改扩建工程建设项目全过程跟踪审计服务-报销单-陈亚5.报销"
    batch_rename_invoices(folder_path)